package com.zsc.oj.job.once;

import com.zsc.oj.mapper.QuestionEsDao;
import com.zsc.oj.model.dto.question.QuestionEsDTO;
import com.zsc.oj.model.entity.Question;
import com.zsc.oj.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * mysql导入es一次性任务
 */
//@Component
@Slf4j
public class MysqlToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;

    @Override
    public void run(String... args) throws Exception {
        //从MySQL获取所有题目
        List<Question> questionList = questionService.list();

        //将题目对象转成ES实体类
        List<QuestionEsDTO> questionEsDTOList = questionList.stream().map(QuestionEsDTO::objToDto).collect(Collectors.toList());

        //分页插入（ES的插入是根据索引下标进行插入的）
        int pageSize = 500;
        int size = questionEsDTOList.size();
        for (int i = 0; i < size; i += pageSize) {
            //同步数据下标不能超过总数量
            int end = Math.min(i+pageSize,size);
            //进行批量插入
            questionEsDao.saveAll(questionEsDTOList.subList(i,end));
        }
        log.info("insert {} ",size);
    }
}
